<template>
  <view class="container">
    <view class="step-wrap">
      <ve-steps :list="stepList" :active="activeStepListIndex" />
    </view>
    <view class="order-create-content" :style="{ 'padding-bottom': activeStepListIndex == 0 ? '130rpx' : '250rpx' }">
      <!-- 订单基础信息 -->
      <view class="basic-info" v-show="activeStepListIndex == 0">
        <ve-form :model="form" ref="formRef" :rules="rules">
          <customer />
          <lease />
          <platoon />
          <contract-card
            v-if="
              !userInfoStore.enterpriseDetail?.contractServiceType?.includes(1) ||
              !userInfoStore.enterpriseDetail.config.userContractServiceType?.includes(1)
            "
          />
        </ve-form>
      </view>
      <!-- 费用信息 -->
      <view class="order-fee-pane" v-show="activeStepListIndex == 1">
        <orderFeePane ref="orderFeePaneRef" />
      </view>
    </view>
    <footer-box id="footer-box">
      <block v-if="activeStepListIndex == 0">
        <ve-button size="long" :disabled="!nextStepIsValid" type="primary" @click="stepClickFn">下一步 去完善费用信息</ve-button>
      </block>
      <template #extra v-if="activeStepListIndex == 1">
        <feeStatistic />
      </template>
      <block v-if="activeStepListIndex == 1">
        <ve-button type="plain" @click="stepClickFn">上一步</ve-button>
        <ve-button type="primary" :loading="okLoading" @click="submitFn">完成</ve-button>
      </block>
    </footer-box>
  </view>
</template>

<script setup name="ShortOrderForm">
  import { ref, provide, computed, nextTick, watch } from 'vue'
  // 组件
  import customer from '@/pages/order/components/customer/index.vue'
  import lease from './components/lease.vue'
  import platoon from './components/platoon.vue'
  import orderFeePane from './components/orderFeePane.vue'
  import footerBox from './components/footerBox.vue'
  import feeStatistic from '../components/order-fee/fee-statistic.vue'
  import contractCard from '../components/contract/contract-card.vue'
  import { getFeeSum } from '../components/order-fee/fee-statistic'
  // ---------------------------
  import { createOrderAPI, calcPriceAPI } from '@/api/order/lOrder'
  import { usePageDict } from '@/hooks/useDict'
  import dayjs from 'dayjs'
  import useFormFold from '@/hooks/useFormFold'
  import { cloneDeep } from '@/utils'
  import useToast from '@/hooks/useToast'
  import { userStore } from '@/stores'
  const userInfoStore = userStore()
  userInfoStore.setEpDetail(false)
  console.log(userInfoStore, 'userInfoStore')

  const dict = usePageDict('longOrderDict')
  provide('dict', dict)

  // 租赁周期限制最小时长 60 分钟
  const timeRangeValidator = (rule, value, callback) => {
    if (value) {
      let start = value[0]
      let end = value[1]
      if (start && end) {
        let months = form.value.leaseMonths
        if (months == 0) {
          callback('租赁周期最小时间范围为1个月')
        }
      }
    }
    callback()
  }
  // 表单规则
  const rules = computed(() => {
    let _rule = {
      memberType: { required: true, message: '请选择客户类型' },
      memberPhone: [
        { required: true, message: '请输入联系电话' },
        { len: 11, match: /^[0-9]+$/, message: '仅支持数字，长度11位' },
      ],
      cardNumber: { match: /^[a-zA-Z0-9]+$/, message: '支持数字、英文' },
      siteId: { required: true, message: '请选择取车门店' },
      orderSource: { required: true, message: '请选择订单来源' },
      originalModelId: { required: true, message: '请选择车型' },

      // 承租人提示根据客户类型区分
      memberName: { required: true, message: form.value.memberType == 2 ? '请输入承租人' : '请选择承租人' },
      timeRange: [{ required: true, message: '请选择预计租赁周期' }, { validator: timeRangeValidator }],
    }
    // 客户类型为公司客户
    if (form.value.memberType == 1) {
      _rule.clientId = { required: true, message: '请选择客户公司名称' }
    }
    // 合同编号必填项
    let contractList = form.value.contractList
    if (contractList[0].fileId) {
      _rule['contractList.0.contractNo'] = [{ required: true, message: '请输入合同编号' }]
    }
    return _rule
  })
  const { foldValidate } = useFormFold([])

  // 表单对象
  const defaultStartTime = dayjs().format('YYYY-MM-DD 00:00:00')
  const form = ref({
    memberType: 2, // 客户类型
    cardType: 0, // 证件类型，默认身份证
    orderSource: 1, // 订单来源
    carSource: 1, // 车辆来源
    // 默认开始时间 开始
    timeRange: [defaultStartTime],
    expectedUseCarTime: defaultStartTime,
    // 默认开始时间 结束
    sendServiceFlag: 0,
    returnServiceFlag: 0,

    // 默认选中分期
    paymentScheme: 2,
    // 默认分期方式
    paymentMethod: 2,
    // 首期付款日默认值
    lnstalmentFirstDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    //合同信息
    contractList: [{ contractTypeName: '租赁合同' }],
  })
  provide('form', form)

  // formRef
  const formRef = ref()

  // feeForm
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1, // 线下、线上费用需要根据选的是渠道订单还是线下订单处理
        feeDetailList: [],
        feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee', 'depositFee'],
      },
    ],
  })
  // 费用类型
  watch(
    () => form.value.orderSource,
    (newVal) => {
      let type = newVal == 1 ? 1 : 2
      feeForm.value.orderFee[0].feeType = type
      console.log(feeForm.value.orderFee[0].feeType)
    },
    { immediate: true },
  )
  provide('feeForm', feeForm)
  // 确认事件
  const orderFeePaneRef = ref()
  const okLoading = ref(false)
  const submitFn = () => {
    // 获取费用信息，第二步
    orderFeePaneRef.value.getCostInfo((costInfo) => {
      let orderFee = feeForm.value.orderFee
      let param = {
        ...form.value,
        ...costInfo,
        orderFee: costInfo.orderFee[0],
        contractAmount: getFeeSum(orderFee),
      }
      // 合同-信息
      let contractList = form.value.contractList
      param.contractFileId = contractList[0].contractFileId
      param.contractNo = contractList[0].contractNo
      param.contractName = contractList[0].contractFileName
      // 删除非接口字段
      let tempParam = cloneDeep(param)
      delete tempParam.contractList
      delete tempParam.timeRange
      delete tempParam.leaseMonths
      delete tempParam.leaseNumberStr
      // 删除部分数据
      okLoading.value = true
      createOrderAPI(tempParam)
        .then((res) => {
          useToast({
            title: '创建成功',
          }).then(() => {
            uni.$emit('operateSuccess', 'create-order')
            uni.navigateBack({
              delta: 1,
            })
          })
        })
        .catch(() => {
          okLoading.value = false
        })
    })
  }
  // 下一步是否可点击
  const nextStepIsValid = computed(() => {
    // 需要判断必填项是否均填写
    let formValue = form.value
    let requiredProp = ['memberName', 'siteId', 'timeRange', 'originalModelId']
    // 个人客户
    if (formValue.memberType == 2) {
      requiredProp.push('memberPhone')
    }
    // 企业客户
    if (formValue.memberType == 1) {
      requiredProp.push('clientId')
    }
    // 合同信息
    if (formValue.contractList?.length > 0) {
      let contract = formValue.contractList[0]
      if (contract.fileId) {
        if (!contract.contractNo) {
          return false
        }
      }
    }
    return !requiredProp.some((item) => !formValue[item])
  })
  // form 聚焦部分字段是否发生变化
  const isChangeFormByProps = (propStrList, prevForm) => {
    let formVal = form.value
    return propStrList.some((prop) => formVal[prop] != prevForm[prop])
  }
  // 点击第二步、第一步事件
  // 步骤条数据
  // 读取门店模板配置，初始化 feeForm
  let prevForm = {}
  const stepList = ['订单信息', '费用信息']
  const activeStepListIndex = ref(0)
  const stepClickFn = () => {
    // 当前 step
    let currStep = activeStepListIndex.value
    // 切换到第二步
    if (currStep == 0) {
      // 第二步可以点击
      if (nextStepIsValid.value) {
        formRef.value.validate((valid, errors) => {
          if (!valid) {
            // 页面滚动到错误位置
            foldValidate(errors, true, '.order-create-content')
          } else {
            console.log('验证通过')
            let formValue = form.value
            if (
              isChangeFormByProps(
                [
                  'siteId',
                  'originalModelId',
                  'returnSiteId',
                  'expectedUseCarTime',
                  'expectedReturnCarTime',
                  'sendServiceFlag',
                  'longitude',
                  'latitude',
                  'returnServiceFlag',
                  'returnLongitude',
                  'returnLatitude',
                ],
                prevForm,
              )
            ) {
              const param = {
                modelId: formValue.originalModelId,
                siteId: formValue.siteId,
                returnSiteId: formValue.returnSiteId,
                startTime: formValue.expectedUseCarTime,
                endTime: formValue.expectedReturnCarTime,
                sendServiceFlag: formValue.sendServiceFlag ? 1 : 0,
                longitude: formValue.longitude,
                latitude: formValue.latitude,
                returnServiceFlag: formValue.returnServiceFlag ? 1 : 0,
                returnLongitude: formValue.returnLongitude,
                returnLatitude: formValue.returnLatitude,
                type: 1, // 1:下单 2：还车 3:续租
              }
              calcPriceAPI(param).then((res) => {
                if (res.result) {
                  activeStepListIndex.value = 1
                  scrollToTopFn()
                  nextTick(() => {
                    orderFeePaneRef.value.initStoreTemplate(prevForm, res.result).then(() => {
                      prevForm = cloneDeep({
                        ...form.value,
                      })
                    })
                  })
                }
              })
            } else {
              activeStepListIndex.value = 1
              scrollToTopFn()
              nextTick(() => {
                orderFeePaneRef.value.initStoreTemplate(prevForm).then(() => {
                  prevForm = cloneDeep({
                    ...form.value,
                  })
                })
              })
            }
          }
        })
      }
    } else {
      activeStepListIndex.value = 0
      scrollToTopFn()
    }
  }

  // 页面滚动到顶部
  const scrollToTopFn = () => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 200,
    })
  }
</script>

<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    background: #f7f8fa;
    .step-wrap {
      border-top: 1px solid #f7f8fa;
      background-color: #ffffff;
      box-shadow: 0rpx 0rpx 30rpx 0rpx rgba(0, 0, 0, 0.05);
      position: relative;
      z-index: 9;
      position: fixed;
      width: 100%;
      left: 0;
    }
    .order-create-content {
      padding: 24rpx;
      padding-top: 178rpx;
      .basic-info {
        /deep/ .ve-card-content {
          padding-bottom: 0;
        }
      }
    }
    #footer-box {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      z-index: 999;
    }
  }
</style>
